package com.kongjs.application.filter;

import com.kongjs.common.mybatis.tenant.TenantContextHolder;
import com.kongjs.common.mybatis.user.UserContextHolder;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
@Component
public class TenantFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String tenantId = null;
        String userId = null;
        try {
            // 使用 jwt 转换JwtAuthenticationToken可以取出jwt信息
            if (authentication instanceof JwtAuthenticationToken jwtAuthenticationToken) {
                Jwt jwt = jwtAuthenticationToken.getToken();
                tenantId = jwt.getClaimAsString("tenantId");
                userId = jwt.getClaimAsString("userId");
                TenantContextHolder.setTenantId(tenantId);
                UserContextHolder.setUserId(userId);
            }
            log.info("[租户ID {}] [用户ID {}] [用户账号 {}] [PATH {}]", tenantId, userId, authentication.getName(), request.getRequestURI());
        } catch (Exception e) {
            log.error("[租户ID {}] [用户ID {}] [用户账号 {}] [PATH {}] [异常 {}]", tenantId, userId, authentication.getName(), request.getRequestURI(), e.getMessage());
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            TenantContextHolder.clearTenantId();
            UserContextHolder.clearUserId();
        }
    }
}
